# This controller handles the login/logout function of the site.  
class SessionsController < ApplicationController
  # Be sure to include AuthenticationSystem in Application Controller instead
  include AuthenticatedSystem

  # render new.rhtml
  def new
    @page_title = "Login"
  end

  def create
    @page_title = "Login"
    self.current_user = User.authenticate(params[:email], params[:password])
    if logged_in?
      if params[:remember_me] == "1"
        current_user.remember_me unless current_user.remember_token?
        cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
      end
      redirect_back_or_default('/')
      flash[:notice] = User.l_attr('successful login')
    else
      if !User.find_by_email(params[:email])
        flash[:error] = "E-mail address not found.  Please <a href=\"/register\">register</a> if you do not yet have an account." 
      elsif !User.authenticate(params[:email], params[:password])
        flash[:error] = "Wrong password.  Please try again or use the 'forgot password' link."
      end 
      redirect_to login_url
    end
  end

  def destroy
    self.current_user.forget_me if logged_in?
    cookies.delete :auth_token
    reset_session
    flash[:notice] = User.l_attr('successful logout')
    redirect_to '/'
  end
end
